package com.carey.blog.action.impl;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.carey.blog.action.util.Filler;
import com.carey.blog.framework.latke.Keys;
import com.carey.blog.framework.latke.action.AbstractCacheablePageAction;
import com.carey.blog.framework.latke.action.ActionException;
import com.carey.blog.framework.latke.action.util.Paginator;
import com.carey.blog.framework.latke.model.Pagination;
import com.carey.blog.framework.latke.model.User;
import com.carey.blog.framework.latke.service.LangPropsService;
import com.carey.blog.framework.latke.util.Locales;
import com.carey.blog.framework.latke.util.Strings;
import com.carey.blog.model.Article;
import com.carey.blog.model.Common;
import com.carey.blog.model.Preference;
import com.carey.blog.repository.ArticleRepository;
import com.carey.blog.repository.UserRepository;
import com.carey.blog.repository.impl.ArticleGAERepository;
import com.carey.blog.repository.impl.UserGAERepository;
import com.carey.blog.util.Preferences;
import com.carey.blog.util.comparator.Comparators;

/**
 * Get articles by author action. author-articles.ftl.
 * 
 */
public final class AuthorArticlesAction extends AbstractCacheablePageAction {

	/**
	 * Default serial version uid.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(AuthorArticlesAction.class.getName());
	/**
	 * Article repository.
	 */
	private ArticleRepository articleRepository = ArticleGAERepository
			.getInstance();
	/**
	 * User repository.
	 */
	private UserRepository userRepository = UserGAERepository.getInstance();
	/**
	 * Filler.
	 */
	private Filler filler = Filler.getInstance();
	/**
	 * Language service.
	 */
	private LangPropsService langPropsService = LangPropsService.getInstance();
	/**
	 * Preference utilities.
	 */
	private Preferences preferenceUtils = Preferences.getInstance();

	@Override
	protected Map<?, ?> doFreeMarkerAction(
			final freemarker.template.Template template,
			final HttpServletRequest request, final HttpServletResponse response)
			throws ActionException {
		final Map<String, Object> ret = new HashMap<String, Object>();

		try {
			final JSONObject preference = preferenceUtils.getPreference();
			if (null == preference) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND);

				return ret;
			}

			final String localeString = preference
					.getString(Preference.LOCALE_STRING);
			final Locale locale = new Locale(Locales.getLanguage(localeString),
					Locales.getCountry(localeString));
			final Map<String, String> langs = langPropsService.getAll(locale);
			ret.putAll(langs);

			final JSONObject queryStringJSONObject = getQueryStringJSONObject(request);
			final String authorId = queryStringJSONObject
					.optString(Keys.OBJECT_ID);
			if (Strings.isEmptyOrNull(authorId)) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND);

				return ret;
			}

			final int currentPageNum = queryStringJSONObject.optInt(
					Pagination.PAGINATION_CURRENT_PAGE_NUM, 1);
			final int pageSize = preference
					.getInt(Preference.ARTICLE_LIST_DISPLAY_COUNT);
			final int windowSize = preference
					.getInt(Preference.ARTICLE_LIST_PAGINATION_WINDOW_SIZE);

			final JSONObject author = userRepository.get(authorId);
			final String authorEmail = author.getString(User.USER_EMAIL);
			final JSONObject result = articleRepository.getByAuthorEmail(
					authorEmail, currentPageNum, pageSize);
			final int pageCount = result.getJSONObject(Pagination.PAGINATION)
					.getInt(Pagination.PAGINATION_PAGE_COUNT);
			final List<Integer> pageNums = Paginator.paginate(currentPageNum,
					pageSize, pageCount, windowSize);

			if (0 != pageNums.size()) {
				ret.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
				ret.put(Pagination.PAGINATION_LAST_PAGE_NUM,
						pageNums.get(pageNums.size() - 1));
			}
			ret.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
			ret.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);

			final List<JSONObject> articles = com.carey.blog.framework.latke.util.CollectionUtils
					.jsonArrayToList(result.getJSONArray(Keys.RESULTS));
			filler.putArticleExProperties(articles, preference);

			if (preference.getBoolean(Preference.ENABLE_ARTICLE_UPDATE_HINT)) {
				Collections.sort(articles,
						Comparators.ARTICLE_UPDATE_DATE_COMPARATOR);
			} else {
				Collections.sort(articles,
						Comparators.ARTICLE_CREATE_DATE_COMPARATOR);
			}
			ret.put(Article.ARTICLES, articles);
			ret.put(Common.ACTION_NAME, Common.AUTHOR_ARTICLES);
			ret.put(Keys.OBJECT_ID, authorId);

			final String authorName = author.getString(User.USER_NAME);
			ret.put(Common.AUTHOR_NAME, authorName);

			filler.fillSide(ret, preference);
			filler.fillBlogHeader(ret, preference);
			filler.fillBlogFooter(ret, preference);
		} catch (final Exception e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);

			try {
				response.sendError(HttpServletResponse.SC_NOT_FOUND);

				return ret;
			} catch (final IOException ex) {
				LOGGER.severe(ex.getMessage());
			}
		}

		return ret;
	}

	@Override
	protected JSONObject doAjaxAction(final JSONObject data,
			final HttpServletRequest request, final HttpServletResponse response)
			throws ActionException {
		throw new UnsupportedOperationException("Not supported yet.");
	}
}
